package leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class 三数之和为0 {
    public static List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        int cur;
        List<List<Integer>> lists = new ArrayList<>();
        int n = nums.length;
        for (int i = 0; i < n; i++) {
            if(nums[i]>0) return lists;
            cur = nums[i];
            int L = i+1;
            int R = n-1;
            if(i>0 && nums[i]==nums[i-1]) {
                continue;
            }

            while (L<R) {
                List<Integer> list = new ArrayList<>();
                int temp = nums[i]+nums[L]+nums[R];
                if (temp==0) {
                    list.add(nums[i]);
                    list.add(nums[L]);
                    list.add(nums[R]);
                    lists.add(list);
                    while (L<R && nums[L]==nums[L+1]) L++;
                    while (L<R && nums[R]==nums[R-1]) R--;
                    R--;
                    L++;
                }
                else if (temp>0) {
                    R--;
                }
                else {
                    L++;
                }
            }
        }
        return lists;
    }

    public static void main(String[] args) {
        System.out.println(threeSum(new int[]{-1,0,1,2,-1,-4}));
    }
}
